package com.ywu.configcenter.jdbc;

import com.ywu.configcenter.entity.ConfigCenterEntity;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName JdbcUtils
 * @Description TODO
 * @Author GroundDemo
 * @Date 2024/2/27 23:20
 * @Version 1.0
 **/
public class JdbcUtils {

    public static Connection getConnection(String driver, String url, String user, String password) throws ClassNotFoundException, SQLException {
        Class.forName(driver);
        return DriverManager.getConnection(url, user, password);
    }

    public static List<ConfigCenterEntity> getConfigByProfileAndApplication(Connection connection, String applicationName, String profile) {
        ArrayList<ConfigCenterEntity> configCenterEntities = new ArrayList<>();
        String sql = "SELECT * FROM ywu_config WHERE application = ? AND profile = ?";
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, applicationName);
            preparedStatement.setString(2, profile);
            // 执行查询数据的SQL语句，获得查询到的结果集
            ResultSet rst = preparedStatement.executeQuery();
            while(rst.next()){
                // 每次调用next()就是将游标移动到结果集的下一行
                // 获取当前行的每列数据，根据列名获取
                int id = (int)rst.getObject("id");
                String key = (String) rst.getObject("key");
                String value = (String) rst.getObject("value");
                ConfigCenterEntity configCenterEntity = new ConfigCenterEntity();
                configCenterEntity.setId(id);
                configCenterEntity.setKey(key);
                configCenterEntity.setValue(value);
                configCenterEntities.add(configCenterEntity);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return configCenterEntities;
    }
}
